<script setup>
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {onBeforeUnmount, ref, shallowRef, watch} from 'vue';
import {baseUrl} from "@/utils/request.js";

const uploadUrl = ref(baseUrl + '/file/upload');

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑模式
const mode = ref('default');

// 接收父组件传递的 modelValue
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
});

// 内容 HTML
const valueHtml = ref(props.modelValue);

// 监听 modelValue 的变化，更新编辑器内容
watch(() => props.modelValue, (newValue) => {
  if (newValue !== valueHtml.value) {
    valueHtml.value = newValue;
  }
});

const toolbarConfig = {};
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const formData = new FormData();
        formData.append('file', file);

        try {
          const response = await fetch(uploadUrl.value, {
            method: 'POST',
            body: formData,
          });
          const result = await response.json();

          if (result.code === 200) {
            const imageUrl = result.data;
            insertFn(imageUrl);
          } else {
            console.error('上传失败:', result.message);
          }
        } catch (error) {
          console.error('上传出错:', error);
        }
      },
    },
    uploadVideo: {
      async customUpload(file, insertFn) {
        const formData = new FormData();
        formData.append('file', file);

        try {
          const response = await fetch('http://192.168.175.1:11111/api/upload', {
            method: 'POST',
            body: formData,
          });
          const result = await response.json();

          if (result.code === 200) {
            const videoUrl = result.data;
            insertFn(videoUrl);
          } else {
            console.error('上传失败:', result.message);
          }
        } catch (error) {
          console.error('上传出错:', error);
        }
      },
    },
  },
};


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  editor.setHtml(valueHtml.value); // 初始化编辑器内容
};

// 监听编辑器内容变化，触发 update:modelValue 事件
const handleChange = (editor) => {
  const html = editor.getHtml();
  if (html !== valueHtml.value) {
    valueHtml.value = html;
    emit('update:modelValue', html);
  }
};

const emit = defineEmits(['update:modelValue']);
</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        :modelValue="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onChange="handleChange"
    />
  </div>
</template>

<style scoped></style>
